package com.example.auction.fragment;

import android.graphics.Bitmap;
import android.widget.*;
import com.example.auction.activity.ItemDetailsViewActivity;
import com.example.auction.sqlite.Sqlite;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.auction.R;
import com.example.auction.activity.UserUIBaseActivity;
import com.example.auction.util.MyUtil;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//装载HomeFragment分类标签下的具体内容
public class TabLayoutKindItemFragment extends Fragment {

    //分类商品展示
    private ListView lv_home_item_list;
    //图文列表适配器
    private SimpleAdapter simpleAdapter;
    //数据源的列表的类型是Map类型（键值对），Map<String（键名），Object（值的类型）>
    private List<Map<String, Object>> kindItemList;
    //类别名字
    private String mKindName;
    private Integer user_id;
    private Sqlite sqlite;
    private Cursor cursor;
    private Bitmap imagebm;

    //是否第一次加载
    private boolean isFirstLoading = true;
    private TextView tv_list_none;

    /**
     * 在fragment可见的时候，刷新数据
     */
    @Override
    public void onResume() {
        super.onResume();

        if (!isFirstLoading) {
            //如果不是第一次加载，刷新数据
            initData();
            inAdapter();
        }

        isFirstLoading = false;
    }

    public TabLayoutKindItemFragment() {

    }

    //接受数据的构造方法
    public TabLayoutKindItemFragment(Integer userId, String kindName) {
        this.user_id = userId;
        this.mKindName = kindName;
        if (userId != 0 && !kindName.equals("")) {

        }
    }


    public static TabLayoutKindItemFragment newInstance(String param1, String param2) {
        TabLayoutKindItemFragment fragment = new TabLayoutKindItemFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tablayout_kind_item, container, false);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //fragment中的数据库对象要在onViewCreat中创建（fragment的生命周期）
        sqlite = new Sqlite((UserUIBaseActivity)getActivity());
        //绑定列表控件
        lv_home_item_list = view.findViewById(R.id.lv_home_item_list);
        tv_list_none = view.findViewById(R.id.tv_list_none);

        //初始化数据
        initData();
        inAdapter();
    }

    private void inAdapter() {
        //初始化适配器
        simpleAdapter = new SimpleAdapter(
                getActivity(),
                //数据源
                kindItemList,
                //列表单个子项的布局文件
                R.layout.list_tablayout_home_kind_item,
                //键的名字，要跟map中的键名对应
                new String[]{"img", "name", "des", "max_price", "owner", "end_time","item_id"},
                //把键名对应的值绑定到控件上，写控件的id
                new int[]{
                        R.id.home_item_list_img,
                        R.id.home_item_list_name,
                        R.id.home_item_list_des,
                        R.id.home_item_list_max_price,
                        R.id.home_item_list_owner,
                        R.id.home_item_list_endtime
                });

        //必须写这个才能显示图片
        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if ((view instanceof ImageView) && (data instanceof Bitmap)) {
                    ImageView imageView = (ImageView) view;
                    Bitmap bitmap = (Bitmap) data;
                    imageView.setImageBitmap(bitmap);
                    return true;
                }
                return false;
            }
        });

        //装载适配器
        lv_home_item_list.setAdapter(simpleAdapter);
        //设置子项点击监听
        lv_home_item_list.setOnItemClickListener(new itemOnClick());
    }

    //初始化数据
    @SuppressLint("Range")
    private void initData() {
        kindItemList = new ArrayList<>();

        /*for (int i = 0; i < 30; i++) {
            Map<String, Object> map = new HashMap<>();
            //向map中存放数据
            map.put("img", R.drawable.test_img2);
            map.put("name", "这是拍卖品名" + (i + 1));
            map.put("des", "这是描述" + (i + 1));
            map.put("max_price", "" + 998);
            map.put("owner", "这是发布者" + (i + 1));
            map.put("end_time", "2023.02.22");
            kindItemList.add(map);
        }*/

        if (mKindName.equals("全部")){
            cursor = sqlite.selectItemByState("已通过", "item_id desc");
        }else {
            cursor = sqlite.selectItemByState(
                    "kind", mKindName, "已通过","item_id desc");
        }
            //循环添加列表子项数据
            while (cursor.moveToNext()) {
                //map用于暂时装载数据
                Map<String, Object> map = new HashMap<>();

                //获取物品id
                Integer item_id = cursor.getInt(cursor.getColumnIndex("item_id"));
                //根据id获取前图片
                imagebm = MyUtil.getImageBySQL(getActivity(),"item",item_id);

                //物品名
                String itemName = cursor.getString(cursor.getColumnIndex("item_name"));
                //描述
                String itemDes = cursor.getString(cursor.getColumnIndex("item_desc"));
                //价格
                String maxPrice = cursor.getString(cursor.getColumnIndex("max_price"));

                //发布者名字
                Integer ownerID = 0;
                ownerID = cursor.getInt(cursor.getColumnIndex("owner_id"));
                String ownerName = MyUtil.getUserNameByID(getActivity(),ownerID);

                //截止时间
                String endTime = cursor.getString(cursor.getColumnIndex("endtime"));


                //打包键值对
                //图片数据库暂时还没做
                map.put("img", imagebm);
                map.put("name", itemName);
                map.put("des", itemDes);
                map.put("max_price", maxPrice);
                map.put("owner", ownerName);
                map.put("end_time", endTime);
                map.put("item_id", item_id.toString());

                //将子项加进列表
                kindItemList.add(map);
            }
        //这个判断要放在装载的下面，否则有拍卖品也显示空白
        if (!cursor.moveToFirst() || cursor == null){
            tv_list_none.setVisibility(View.VISIBLE);
        }else {
            tv_list_none.setVisibility(View.GONE);
        }

    }

    //子项点击跳转到对应拍卖品竞价页
    private class itemOnClick implements android.widget.AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            String item_id = kindItemList.get(position).get("item_id").toString().trim();
            Toast.makeText(getActivity(), "您选择的是：" + item_id, Toast.LENGTH_SHORT).show();

            //将用户id以及点击的拍卖品名传给拍卖品竞价页
            Intent intent = new Intent();
            intent.putExtra("user_id", user_id);
            intent.putExtra("item_id", item_id);
            //传递从哪个页面跳转过去的信标
            intent.putExtra("from", "home");
            intent.setClass(getActivity(), ItemDetailsViewActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }

}